﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Moven.Data;

namespace Moven.ViewModels
{
    class TagsViewModel: BaseViewModel
    {
        public TagsViewModel()
        {
            Title = "标签分类";
            Icon = "tag.png";
            
            _items = new ObservableCollection<TagItem>(GetTagItems());
			Statics.ArticlesStore.ArticlesRefreshed += (_, result) =>
            {
				if (result.Status == RefreshArticlesStatus.Failure)
				{
					return;
				}
				var newArticles = result.NewArticles;
				if (newArticles.IsNullOrEmpty())
				{
					return;
				}
				var dictionary = Items.ToDictionary(x => x.Name);
				var newTagItems = new List<TagItem>();
				foreach (var article in newArticles)
				{
					foreach (var tag in article.Tags)
					{
						if (dictionary.ContainsKey(tag))
						{
							dictionary[tag].Count++;
						}
						else
						{
							var newTagItem = new TagItem
							{
								Name = tag,
								Count = 1
							};
							newTagItems.Add(newTagItem);
							dictionary[tag] = newTagItem;
						}
					}
				}

				var sortedItems = Items.ToList();
				sortedItems.Sort((x, y) => y.Count - x.Count);
				for (int i = 0; i < Items.Count; i++)
				{
					Items[i] = sortedItems[i];
				}

				foreach (var newTagItem in newTagItems)
				{
					for (int i = 0; i < Items.Count; i++)
					{
						bool isMinCounted = true;
						if (newTagItem.Count >= Items[i].Count)
						{
							isMinCounted = false;
							Items.Insert(i, newTagItem);
							break;
						}
						if (isMinCounted)
						{
							Items.Add(newTagItem);
						}
					}
				}
            };
        }

        List<TagItem> GetTagItems()
        {
            var tags = Statics.ArticlesStore.GetTagsAsync().Result;
            return tags.Select(x => new TagItem { Name = x.Name, Count = x.Count }).ToList();
        }

        ObservableCollection<TagItem> _items;
        public ObservableCollection<TagItem> Items
        {
            get { return _items; }
            set { SetProperty(ref _items, value); }
        }

        public class TagItem
        {
            public string Name { get; set; }
            public int Count { get; set; }
            public string Text => Name + " [" + Count + "篇]";
        }
    }
}
